package com.ist.word.datasoure;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.sqlite.JDBC;
import org.sqlite.SQLite;

public class SQLiteDataSource {
	private static Connection conn;

	public Connection getConneection() throws Exception {

		//String databasePath=getDBTempFilePath("/database/DictEn.db","DictEn.db");
		//databasePath = URLDecoder.decode(databasePath, "utf-8");

		String databasePath = System.getProperty("user.dir") + "/database/DictEn.db";
		databasePath = URLDecoder.decode(databasePath, "UTF-8");
		
		Class.forName("org.sqlite.JDBC");
		conn = DriverManager.getConnection("jdbc:sqlite://" + databasePath);
		conn.setAutoCommit(false);
		return conn;
	}
	/*
	public static void main(String[] args) throws SQLException, Exception {
		System.out.println(new SQLiteDataSource().getDBTempFilePath("/database/DictEn.db","DictEn.db"));
	}*/

	// 从jar包中获取db文件 并创建临时的db文件
	public String getDBTempFilePath(String dbJarPathString,String dbName) throws Exception {
		InputStream dbInputStream = this.getClass().getResourceAsStream(dbJarPathString);
		// 创建保存文件
		File file = new File(System.getProperty("java.io.tmpdir")+dbName);
		if (file.exists()) {
			return file.getPath();
		}
		// 得到数据
		byte[] data = readInStream(dbInputStream);
		// 创建一个文件输出流
		FileOutputStream outputStream = new FileOutputStream(file);

		// 将我们所得的二进制数据全部写入我们建好的文件中
		outputStream.write(data);
		outputStream.flush();
		// 关闭输出流
		outputStream.close();
		return file.getPath();

	}

	// 读取流文件的内容
	public byte[] readInStream(InputStream inputStream) throws Exception {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// 声明缓冲区
		byte[] buffer = new byte[1024];
		// 定义读取默认长度
		int length = -1;
		while ((length = inputStream.read(buffer)) != -1) {
			// 把缓冲区中输出到内存中
			byteArrayOutputStream.write(buffer, 0, length);
		}
		// 关闭输出流
		byteArrayOutputStream.close();
		// 关闭输入流
		inputStream.close();
		// 返回这个输出流的字节数组
		return byteArrayOutputStream.toByteArray();

	}


}
